import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  OnChanges,
  SimpleChanges,
  ChangeDetectorRef,
  ChangeDetectionStrategy
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { MemberService } from '@services/member.service';
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
import { ModalTypes } from '@store/reducers/member.reducer';
import { BatchActionsService } from '@store/batch-actions.service';

enum Exist {
  'exist' = 1,
  'no_exist' = -1
}

@Component({
  selector: 'app-wyy-layer-register',
  templateUrl: './wyy-layer-register.component.html',
  styleUrls: ['./wyy-layer-register.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class WyyLayerRegisterComponent implements OnInit, OnChanges {
  formModel: FormGroup;
  timing: number;
  showSmsCode = false;
  codePassed: string | boolean = '';
  @Input() visible: boolean;
  @Output() onRegister = new EventEmitter<string>();
  @Output() onChangeModalType = new EventEmitter<string>();
  constructor(
    private fb: FormBuilder,
    private memberService: MemberService,
    private nzMessageService: NzMessageService,
    private batchActionsService: BatchActionsService,
    private cdr: ChangeDetectorRef
  ) {
    this.formModel = this.fb.group({
      phone: ['', [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      password: ['', [Validators.required, Validators.minLength(6)]]
    });
  }

  ngOnInit() {
  }
  ngOnChanges(changes: SimpleChanges) {
    const visible = changes.visible;
    // 弹窗关闭后，表单重置
    if (visible && !visible.previousValue) {
      this.formModel.reset();
    }
    if (visible && !visible.firstChange) {
      this.formModel.markAllAsTouched();
      if (!this.visible) {
        this.showSmsCode = false;
      }
    }
  }
  onSubmit() {
    const model = this.formModel;
    if (model.valid) {
      this.sendSmsCode();
    }
  }
  onCheckCode(code: string) {
    const phone = this.formModel.get('phone').value;
    this.memberService.checkSmsCode(phone, Number(code)).subscribe(() => {
      this.codePassed = true;
    }, () => {
      this.codePassed = false;
    }, () => {
      this.cdr.markForCheck();
    });
  }
  onCheckExist() {
    const phone = this.formModel.get('phone').value;
    this.memberService.checkPhoneExists(Number(phone)).subscribe((res) => {
      if (Exist[res] === 'exist') {
        this.nzMessageService.error('账号已存在，请直接登录');
        this.changeType(ModalTypes.LoginByPhone);
      } else if (Exist[res] === 'no_exist') {
        this.onRegister.emit(phone);
        this.batchActionsService.controlModalVisible(false, ModalTypes.Register);
      }
    });
  }
  changeType(type = ModalTypes.Register) {
    this.showSmsCode = true;
    this.onChangeModalType.emit(type);
  }
  sendSmsCode() {
    const phone = this.formModel.get('phone').value;
    this.memberService.sendSmsCode(phone).subscribe(() => {
        this.timing = 60;
        if (!this.showSmsCode) {
          this.showSmsCode = true;
        }
        this.cdr.markForCheck();
        interval(1000).pipe(take(60)).subscribe(() => {
          this.timing--;
          this.cdr.markForCheck();
        });
      }, error => {
      this.nzMessageService.create('error', error.msg || '验证码发送失败');
    });
  }
}
